class Snake {
    constructor() {
        this.body = [
            { x: 10, y: 10 },
            { x: 9, y: 10 },
            { x: 8, y: 10 }
        ];
        this.direction = 'right';
        this.nextDirection = 'right';
    }

    move() {
        this.direction = this.nextDirection;
        const head = { ...this.body[0] };

        switch (this.direction) {
            case 'up': head.y--; break;
            case 'down': head.y++; break;
            case 'left': head.x--; break;
            case 'right': head.x++; break;
        }

        this.body.unshift(head);
        return this.body.pop();
    }

    grow() {
        const tail = this.body[this.body.length - 1];
        this.body.push({ ...tail });
    }

    checkCollision(width, height) {
        const head = this.body[0];
        if (head.x < 0 || head.x >= width || head.y < 0 || head.y >= height) {
            return true;
        }
        return this.body.slice(1).some(segment =>
            segment.x === head.x && segment.y === head.y
        );
    }
}

class Game {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.gridSize = 20;
        this.width = this.canvas.width / this.gridSize;
        this.height = this.canvas.height / this.gridSize;
        
        this.snake = new Snake();
        this.food = this.generateFood();
        this.score = 0;
        this.highScore = parseInt(localStorage.getItem('highScore')) || 0;
        this.speed = 5;
        this.isRunning = false;
        this.gameLoop = null;

        this.bindControls();
        this.initializeGame();
    }

    generateFood() {
        let food;
        do {
            food = {
                x: Math.floor(Math.random() * this.width),
                y: Math.floor(Math.random() * this.height)
            };
        } while (this.snake.body.some(segment =>
            segment.x === food.x && segment.y === food.y
        ));
        return food;
    }

    bindControls() {
        document.addEventListener('keydown', (e) => {
            switch (e.key) {
                case 'ArrowUp':
                    if (this.snake.direction !== 'down') {
                        this.snake.nextDirection = 'up';
                    }
                    break;
                case 'ArrowDown':
                    if (this.snake.direction !== 'up') {
                        this.snake.nextDirection = 'down';
                    }
                    break;
                case 'ArrowLeft':
                    if (this.snake.direction !== 'right') {
                        this.snake.nextDirection = 'left';
                    }
                    break;
                case 'ArrowRight':
                    if (this.snake.direction !== 'left') {
                        this.snake.nextDirection = 'right';
                    }
                    break;
            }
        });

        document.getElementById('speed').addEventListener('input', (e) => {
            this.speed = parseInt(e.target.value);
            document.getElementById('speedValue').textContent = this.speed;
            if (this.isRunning) {
                this.stop();
                this.start();
            }
        });

        document.getElementById('startBtn').addEventListener('click', () => {
            if (this.isRunning) {
                this.stop();
                document.getElementById('startBtn').textContent = '开始游戏';
            } else {
                this.start();
                document.getElementById('startBtn').textContent = '暂停游戏';
            }
        });

        document.getElementById('restartBtn').addEventListener('click', () => {
            this.reset();
        });
    }

    initializeGame() {
        // 设置画布背景
        this.ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

        // 绘制网格
        this.ctx.strokeStyle = 'rgba(0, 247, 255, 0.1)';
        for (let i = 0; i <= this.width; i++) {
            this.ctx.beginPath();
            this.ctx.moveTo(i * this.gridSize, 0);
            this.ctx.lineTo(i * this.gridSize, this.canvas.height);
            this.ctx.stroke();
        }
        for (let i = 0; i <= this.height; i++) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, i * this.gridSize);
            this.ctx.lineTo(this.canvas.width, i * this.gridSize);
            this.ctx.stroke();
        }

        this.draw();
    }

    draw() {
        // 清空画布
        this.ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

        // 绘制网格
        this.ctx.strokeStyle = 'rgba(0, 247, 255, 0.1)';
        for (let i = 0; i <= this.width; i++) {
            this.ctx.beginPath();
            this.ctx.moveTo(i * this.gridSize, 0);
            this.ctx.lineTo(i * this.gridSize, this.canvas.height);
            this.ctx.stroke();
        }
        for (let i = 0; i <= this.height; i++) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, i * this.gridSize);
            this.ctx.lineTo(this.canvas.width, i * this.gridSize);
            this.ctx.stroke();
        }

        // 绘制食物
        const gradient = this.ctx.createRadialGradient(
            (this.food.x + 0.5) * this.gridSize,
            (this.food.y + 0.5) * this.gridSize,
            2,
            (this.food.x + 0.5) * this.gridSize,
            (this.food.y + 0.5) * this.gridSize,
            this.gridSize / 2
        );
        gradient.addColorStop(0, '#ff0066');
        gradient.addColorStop(1, '#ff0000');
        this.ctx.fillStyle = gradient;
        this.ctx.beginPath();
        this.ctx.arc(
            (this.food.x + 0.5) * this.gridSize,
            (this.food.y + 0.5) * this.gridSize,
            this.gridSize / 2 - 2,
            0,
            Math.PI * 2
        );
        this.ctx.fill();

        // 绘制蛇
        this.snake.body.forEach((segment, index) => {
            const gradient = this.ctx.createLinearGradient(
                segment.x * this.gridSize,
                segment.y * this.gridSize,
                (segment.x + 1) * this.gridSize,
                (segment.y + 1) * this.gridSize
            );
            gradient.addColorStop(0, index === 0 ? '#00ff88' : '#00f7ff');
            gradient.addColorStop(1, index === 0 ? '#00f7ff' : '#00ff88');
            this.ctx.fillStyle = gradient;

            // 绘制圆角矩形
            const radius = 4;
            const x = segment.x * this.gridSize;
            const y = segment.y * this.gridSize;
            const width = this.gridSize - 2;
            const height = this.gridSize - 2;

            this.ctx.beginPath();
            this.ctx.moveTo(x + radius, y);
            this.ctx.lineTo(x + width - radius, y);
            this.ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
            this.ctx.lineTo(x + width, y + height - radius);
            this.ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
            this.ctx.lineTo(x + radius, y + height);
            this.ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
            this.ctx.lineTo(x, y + radius);
            this.ctx.quadraticCurveTo(x, y, x + radius, y);
            this.ctx.closePath();
            this.ctx.fill();

            // 为蛇头添加眼睛
            if (index === 0) {
                this.ctx.fillStyle = '#000';
                const eyeSize = 3;
                const eyeOffset = 5;
                let eyeX1, eyeY1, eyeX2, eyeY2;

                switch (this.snake.direction) {
                    case 'right':
                        eyeX1 = eyeX2 = x + width - eyeOffset;
                        eyeY1 = y + eyeOffset;
                        eyeY2 = y + height - eyeOffset;
                        break;
                    case 'left':
                        eyeX1 = eyeX2 = x + eyeOffset;
                        eyeY1 = y + eyeOffset;
                        eyeY2 = y + height - eyeOffset;
                        break;
                    case 'up':
                        eyeY1 = eyeY2 = y + eyeOffset;
                        eyeX1 = x + eyeOffset;
                        eyeX2 = x + width - eyeOffset;
                        break;
                    case 'down':
                        eyeY1 = eyeY2 = y + height - eyeOffset;
                        eyeX1 = x + eyeOffset;
                        eyeX2 = x + width - eyeOffset;
                        break;
                }

                this.ctx.beginPath();
                this.ctx.arc(eyeX1, eyeY1, eyeSize, 0, Math.PI * 2);
                this.ctx.arc(eyeX2, eyeY2, eyeSize, 0, Math.PI * 2);
                this.ctx.fill();
            }
        });
    }

    update() {
        const oldTail = this.snake.move();

        // 检查是否吃到食物
        if (this.snake.body[0].x === this.food.x && this.snake.body[0].y === this.food.y) {
            this.snake.grow();
            this.food = this.generateFood();
            this.score += 10;
            document.getElementById('score').textContent = `分数：${this.score}`;
            if (this.score > this.highScore) {
                this.highScore = this.score;
                localStorage.setItem('highScore', this.highScore);
                document.getElementById('highScore').textContent = `最高分：${this.highScore}`;
            }
        }

        // 检查碰撞
        if (this.snake.checkCollision(this.width, this.height)) {
            this.stop();
            alert(`游戏结束！最终得分：${this.score}`);
            this.reset();
            return;
        }

        this.draw();
    }

    start() {
        if (!this.isRunning) {
            this.isRunning = true;
            this.gameLoop = setInterval(() => this.update(), 1000 / (this.speed + 5));
        }
    }

    stop() {
        if (this.isRunning) {
            this.isRunning = false;
            clearInterval(this.gameLoop);
            this.gameLoop = null;
            document.getElementById('startBtn').textContent = '开始游戏';
        }
    }

    reset() {
        this.snake = new Snake();
        this.food = this.generateFood();
        this.score = 0;
        document.getElementById('score').textContent = '分数：0';
        document.getElementById('startBtn').textContent = '开始游戏';
        this.draw();
    }
}

// 初始化游戏
const game = new Game();